<template>
  <view class="post-detail-container">
    <view v-if="loading" class="loading">
      <uni-load-more status="loading" />
    </view>

    <template v-else-if="currentPost">
      <!-- 帖子内容 -->
      <view class="post-card">
        <view class="post-header">
          <view class="user-info">
            <image :src="currentPost.avatar" class="avatar" mode="aspectFill" />
            <view class="user-detail">
              <text class="username">{{
                currentPost.user || currentPost.user_name || "匿名用户"
              }}</text>
              <text class="time">{{
                currentPost.create_time
                  ? formatTime(currentPost.create_time)
                  : "未知时间"
              }}</text>
            </view>
          </view>
        </view>

        <view class="post-content">
          <text class="title">{{ currentPost.title || "" }}</text>
          <text class="content">{{ currentPost.content || "" }}</text>

          <!-- 图片展示 -->
          <view
            v-if="currentPost.images && currentPost.images.length"
            class="image-grid"
          >
            <image
              v-for="(image, index) in currentPost.images"
              :key="index"
              :src="url('c', index, 'jpg')"
              mode="aspectFill"
              class="post-image"
              @tap="previewImage(index)"
            />
          </view>
        </view>

        <view class="post-footer">
          <view class="action-btn" @tap="toggleLike">
            <text
              class="bi"
              :class="isLiked ? 'bi-heart-fill' : 'bi-heart'"
            ></text>
            <text>{{ likeCount }}</text>
          </view>
          <view class="action-btn" @tap="focusComment">
            <text class="bi bi-chat"></text>
            <text>{{ allComments.length }}</text>
          </view>
        </view>
      </view>

      <!-- 评论列表 -->
      <view class="comments-section">
        <text class="section-title">评论 ({{ allComments.length }})</text>

        <view class="comment-list">
          <view
            v-for="(comment, index) in allComments"
            :key="index"
            class="comment-item animate__animated animate__fadeIn"
          >
            <view class="comment-header">
              <image
                :src="comment.avatar"
                class="comment-avatar"
                mode="aspectFill"
              />
              <view class="comment-info">
                <text class="comment-username">{{ comment.user_name }}</text>
                <text class="comment-time">{{ formatTime(comment.time) }}</text>
              </view>
            </view>
            <text class="comment-content">{{ comment.content }}</text>
          </view>
        </view>
      </view>

      <!-- 底部评论输入框 -->
      <view class="comment-input-bar">
        <uni-easyinput
          v-model="newComment"
          placeholder="说点什么..."
          :clearable="true"
          @confirm="submitComment"
        >
          <template #prefixIcon>
            <uni-icons type="chat" size="20" color="#666"></uni-icons>
          </template>
        </uni-easyinput>
        <button class="submit-btn" @tap="submitComment">发送</button>
      </view>
    </template>

    <template v-else>
      <view class="error-message">
        <text>加载失败，请刷新重试</text>
        <button class="refresh-btn" @tap="refreshPage">刷新</button>
      </view>
    </template>
  </view>
</template>

<script setup>
import { ref, onMounted, computed, watchEffect, nextTick } from "vue";
import moment from "moment";
import { useForumStore } from "@/stores/forumStore";
import { useUserStore } from "@/stores/userStore";
import { storeToRefs } from "pinia";

const url = $url;
// 添加云函数基础URL
const API_URL =
  "https://fc-mp-d7d620be-76ea-43bb-a05a-d38ceb13c655.next.bspapp.com/comment";
// 添加腾讯云数据万象文本审核API
const CI_TEXT_MODERATION_URL = "https://ci.tencentcloudapi.com";
const forumStore = useForumStore();
const userStore = useUserStore();
const { loading } = storeToRefs(forumStore);
const currentPost = ref(null);
const comments = ref([]);
const newComment = ref("");
const postId = ref("");

// 只使用实际评论
const allComments = computed(() => {
  const realComments = currentPost.value?.comments || [];
  return [...realComments].sort((a, b) => {
    return new Date(b.time) - new Date(a.time);
  });
});

// 点赞状态
const isLiked = computed(() => currentPost.value?.islinked === 1);
const likeCount = computed(() => currentPost.value?.likes || 0);

// 获取帖子详情
onMounted(() => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const pagePostId = currentPage.options?.id;

  if (pagePostId) {
    postId.value = pagePostId;
    console.log("页面加载，帖子ID:", postId.value);
    fetchPostDetail(postId.value);
  }
});

// 刷新页面
const refreshPage = () => {
  if (postId.value) {
    fetchPostDetail(postId.value);
  }
};

// 获取帖子详情 - 修改为使用原生请求而不是云函数
const fetchPostDetail = async (id) => {
  try {
    loading.value = true;
    console.log("正在获取帖子详情，ID:", id);

    // 使用forumStore或直接请求获取数据
    if (forumStore && typeof forumStore.fetchPostDetail === "function") {
      await forumStore.fetchPostDetail(id);
      if (forumStore.currentPost) {
        currentPost.value = forumStore.currentPost;
        comments.value = currentPost.value.comments || [];
        console.log("从store获取到帖子详情:", currentPost.value);
      } else {
        throw new Error("帖子不存在");
      }
    } else {
      // 使用uni.request作为备选方案
      const response = await uni.request({
        url: API_URL,
        method: "POST",
        data: {
          action: "getPostDetail",
          postId: id,
        },
      });

      if (response.data && response.data.status === 1) {
        currentPost.value = response.data.data;
        comments.value = currentPost.value.comments || [];
      } else {
        throw new Error("获取帖子详情失败");
      }
    }
  } catch (error) {
    console.error("获取帖子详情失败:", error);
    uni.showToast({
      title: "获取帖子详情失败",
      icon: "none",
    });

    // 使用简单的模拟数据作为最后备选
    currentPost.value = {
      _id: id,
      user: "测试用户",
      title: "加载失败的帖子",
      content: "无法加载帖子详情，请稍后重试。",
      create_time: new Date().toISOString(),
      likes: 0,
      islinked: 0,
      comments: [],
    };
  } finally {
    loading.value = false;
  }
};

// 点赞 - 修改为使用forumStore或直接请求
const toggleLike = async () => {
  if (!currentPost.value) return;

  try {
    // 乐观更新UI
    const newIsLiked = currentPost.value.islinked === 1 ? 0 : 1;
    currentPost.value.islinked = newIsLiked;
    currentPost.value.likes = newIsLiked
      ? (currentPost.value.likes || 0) + 1
      : (currentPost.value.likes || 0) - 1;

    // 发送请求更新服务器
    if (forumStore && typeof forumStore.likePost === "function") {
      await forumStore.likePost(currentPost.value._id);
    } else {
      // 使用uni.request作为备选
      await uni.request({
        url: API_URL,
        method: "POST",
        data: {
          action: "likePost",
          postId: currentPost.value._id,
        },
      });
    }

    uni.showToast({
      title: newIsLiked ? "点赞成功" : "已取消点赞",
      icon: "success",
    });
  } catch (error) {
    console.error("点赞失败:", error);
    // 还原UI状态
    currentPost.value.islinked = currentPost.value.islinked === 1 ? 0 : 1;
    currentPost.value.likes =
      currentPost.value.islinked === 1
        ? (currentPost.value.likes || 0) + 1
        : (currentPost.value.likes || 0) - 1;

    uni.showToast({
      title: "操作失败",
      icon: "none",
    });
  }
};

// 整合的违禁词过滤函数
const filterComment = (text) => {
  // 自定义敏感词列表
  const sensitiveWords = ["傻逼","垃圾","妈","爸","废物","狗屎","混蛋","白痴","政","草","买一送一","加我",
  "暴","色情","赌博","毒品","诈骗","侮辱","歧视","恐怖","血","免费","特价促销","稳赚不赔","包赔",
  "点击有奖","共产党","领导人姓名","政府","游行","示威","脑残","蠢货","low逼","贱人","去死","傻B","cao","fuck",
  "bitch","尼玛","绝对有效","百分百","史上最强","独家秘方","根治","枪击案","爆炸物","自杀式","人质","恐怖袭击","代开发票"
  ,"迷药","外挂","作弊器","招嫖","艹","cnm"
  ];

  // 违法内容正则
  const illegalPatterns = [
    /[0-9]{11}/, // 手机号
    /[1-9][0-9]{4,}/, // QQ号
    /(https?|ftp):\/\/[^\s/$.?#].[^\s]*/, // 网址
    /微信\s*[:：]?\s*[a-zA-Z0-9_-]{6,}/, // 微信号
  ];

  let filteredText = text;

  // 替换敏感词
  sensitiveWords.forEach((word) => {
    const reg = new RegExp(word, "gi");
    filteredText = filteredText.replace(reg, "*".repeat(word.length));
  });

  // 替换违法内容
  illegalPatterns.forEach((pattern) => {
    filteredText = filteredText.replace(pattern, "***");
  });

  // 检查是否包含敏感内容
  const hasSensitiveContent = filteredText !== text;

  return {
    text: filteredText,
    hasSensitiveContent,
  };
};

// 腾讯云数据万象文本审核
const ciTextModeration = async (text) => {
  try {
    // 调用腾讯云数据万象的文本审核API
    const response = await uni.request({
      url: API_URL,
      method: "POST",
      data: {
        action: "ciTextModeration",
        text: text
      }
    });
    
    if (response.data && response.data.status === 1) {
      const result = response.data.data;
      console.log('腾讯云文本审核结果:', result);
      
      // 判断是否通过审核
      // 根据腾讯云返回结果判断，如果有敏感内容(Suggestion为Block或Review)则不通过
      if (result.Suggestion === 'Block') {
        return {
          passed: false,
          reason: '内容包含违规信息，无法发布',
          details: result
        };
      } else if (result.Suggestion === 'Review') {
        // 需要人工审核的内容，可以根据业务需求决定是否通过
        return {
          passed: false,
          reason: '内容需要审核，暂时无法发布',
          details: result
        };
      }
      
      return {
        passed: true,
        details: result
      };
    } else {
      console.error('腾讯云文本审核API调用失败:', response.data);
      // API调用失败时，回退到本地敏感词过滤
      return { passed: true, fallback: true };
    }
  } catch (error) {
    console.error('腾讯云文本审核异常:', error);
    // 发生异常时，回退到本地敏感词过滤
    return { passed: true, fallback: true };
  }
};

// 综合型验证函数
const validateComment = async (content) => {
  // 空内容检查
  if (!content || !content.trim()) {
    return { valid: false, reason: "评论内容不能为空" };
  }

  // 长度检查
  if (content.length < 2) {
    return { valid: false, reason: "评论内容太短" };
  }

  if (content.length > 200) {
    return { valid: false, reason: "评论内容不能超过200字" };
  }

  // 重复字符检查
  const repeatedChar = /(.)\1{5,}/;
  if (repeatedChar.test(content)) {
    return { valid: false, reason: "评论内容包含过多重复字符" };
  }

  // 首先调用腾讯云数据万象文本审核
  const ciResult = await ciTextModeration(content);
  
  if (!ciResult.passed) {
    return {
      valid: false,
      reason: ciResult.reason || "评论内容不符合规范",
    };
  }
  
  // 如果腾讯云审核API调用失败或异常，回退到本地敏感词过滤
  if (ciResult.fallback) {
    // 本地敏感内容检查
    const { text: filteredContent, hasSensitiveContent } = filterComment(content);

    if (hasSensitiveContent) {
      return {
        valid: false,
        reason: "评论包含不当内容",
        filteredContent,
      };
    }
    
    return { valid: true, filteredContent: content };
  }
  
  // 腾讯云审核通过
  return { valid: true, filteredContent: content };
};

// 提交评论
const submitComment = async () => {
  try {
    uni.showLoading({
      title: '内容审核中...'
    });
    
    // 验证评论内容 (已改为异步)
    const validation = await validateComment(newComment.value);
    
    uni.hideLoading();
    
    if (!validation.valid) {
      uni.showToast({
        title: validation.reason,
        icon: "none",
      });
      return;
    }

    // 确保帖子存在
    if (!currentPost.value) {
      uni.showToast({
        title: "帖子数据不存在",
        icon: "none",
      });
      return;
    }

    // 获取用户信息
    const userName = userStore?.userInfo?.user_name || "当前用户";
    const userAvatar =
      userStore?.userInfo?.avatar ||
      "https://pic1.imgdb.cn/item/678e5c23d0e0a243d4f5f76d.png";

    // 准备评论数据
    const commentData = {
      user_name: userName,
      avatar: userAvatar,
      content: validation.filteredContent,
      time: new Date().toISOString(),
      likes: 0,
    };

    // 发送请求保存到服务器
    const response = await uni.request({
      url: API_URL,
      method: "POST",
      data: {
        action: "addComment",
        postId: currentPost.value._id,
        commentData,
      },
    });

    if (response.data.status === 1) {
      // 更新本地状态
      if (!currentPost.value.comments) {
        currentPost.value.comments = [];
      }
      currentPost.value.comments.unshift(commentData);
      currentPost.value.comment = (currentPost.value.comment || 0) + 1;

      // 清空输入框
      newComment.value = "";

      uni.showToast({
        title: "评论成功",
        icon: "success",
      });
    }
  } catch (error) {
    console.error("评论失败:", error);
    uni.showToast({
      title: "评论失败",
      icon: "none",
    });
  }
};

// 预览图片 - 添加安全检查
const previewImage = (index) => {
  if (
    !currentPost.value ||
    !currentPost.value.images ||
    !currentPost.value.images.length
  ) {
    uni.showToast({
      title: "该帖子没有图片",
      icon: "none",
    });
    return;
  }

  const urls = currentPost.value.images.map((i) => url("c", i, "jpg"));
  uni.previewImage({
    urls,
    current: index,
  });
};

// 格式化时间
const formatTime = (time) => {
  if (!time) return "未知时间";
  return moment(time).fromNow();
};

// 获取随机整数
const getRandomInt = (min, max) => {
  return Math.floor(Math.random() * (max - min + 1)) + min;
};

// 获取渐变背景
const getGradientBackground = () => {
  const colors = [
    ["#ff9a9e", "#fad0c4"],
    ["#a18cd1", "#fbc2eb"],
    ["#fad0c4", "#ffd1ff"],
  ];
  const [color1, color2] = colors[Math.floor(Math.random() * colors.length)];
  return `linear-gradient(45deg, ${color1} 0%, ${color2} 100%)`;
};

// 聚焦评论输入框
const focusComment = () => {
  uni.pageScrollTo({
    selector: ".comment-input-bar",
    duration: 300,
  });
};
// 添加了腾讯云数据万象文本审核API的相关配置
// 实现了ciTextModeration函数，用于调用腾讯云文本审核服务
// 将评论验证改为异步方式，先使用腾讯云审核，如果API调用失败再回退到本地敏感词过滤
// 添加了isAuditing标志来防止重复提交评论
// 优化了整个评论提交流程，包括添加加载提示和错误处理
// 现在当用户提交评论时：
// 首先通过腾讯云数据万象的API进行文本审核
// 如果审核不通过，会向用户显示相应的提示信息
// 如果审核通过，则继续发布评论
// 如果API调用失败，会回退到本地敏感词过滤机制
// 这种方式提供了更全面的内容审核，并具有良好的容错处理。
</script>

<style lang="scss" scoped>
.post-detail-container {
  min-height: 100vh;
  background: #f5f7fa;
  padding-bottom: 120rpx;
}

.post-card {
  background: #ffffff;
  padding: 40rpx;
  margin: 20rpx;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
}

.post-header {
  margin-bottom: 30rpx;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 24rpx;
}

.avatar {
  width: 88rpx;
  height: 88rpx;
  border-radius: 50%;
  border: 4rpx solid #ffffff;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.user-detail {
  display: flex;
  flex-direction: column;
  gap: 8rpx;

  .username {
    font-size: 32rpx;
    font-weight: 600;
    color: #333333;
  }

  .time {
    font-size: 24rpx;
    color: #999999;
  }
}

.post-content {
  margin: 30rpx 0;

  .title {
    font-size: 40rpx;
    font-weight: 600;
    color: #333333;
    margin-bottom: 24rpx;
    display: block;
    line-height: 1.4;
  }

  .content {
    font-size: 30rpx;
    color: #666666;
    line-height: 1.8;
    letter-spacing: 0.5rpx;
  }
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16rpx;
  margin-top: 30rpx;

  .post-image {
    width: 100%;
    height: 220rpx;
    border-radius: 12rpx;
    object-fit: cover;
    transition: transform 0.3s ease;

    &:active {
      transform: scale(0.98);
    }
  }
}

.post-footer {
  display: flex;
  gap: 40rpx;
  margin-top: 30rpx;
  padding-top: 30rpx;
  border-top: 2rpx solid rgba(0, 0, 0, 0.05);
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 12rpx;
  color: #666666;
  font-size: 28rpx;
  transition: color 0.3s ease;

  &:active {
    opacity: 0.8;
  }

  .bi-heart-fill {
    color: #ff4757;
  }
}

.comments-section {
  background: #ffffff;
  padding: 40rpx;
  margin: 20rpx;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);

  .section-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333333;
    margin-bottom: 30rpx;
    display: block;
  }
}

.comment-item {
  padding: 24rpx 0;
  border-bottom: 2rpx solid #f5f5f5;

  &:last-child {
    border-bottom: none;
  }
}

.comment-header {
  display: flex;
  align-items: center;
  gap: 20rpx;
  margin-bottom: 16rpx;
}

.comment-avatar {
  width: 64rpx;
  height: 64rpx;
  border-radius: 50%;
  border: 2rpx solid #ffffff;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.comment-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4rpx;
}

.comment-username {
  font-size: 28rpx;
  font-weight: 600;
  color: #333333;
}

.comment-time {
  font-size: 24rpx;
  color: #999999;
}

.comment-content {
  font-size: 28rpx;
  color: #666666;
  line-height: 1.6;
  padding-left: 84rpx;
}

.comment-input-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #ffffff;
  padding: 24rpx;
  display: flex;
  gap: 24rpx;
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.05);
  backdrop-filter: blur(10px);
}

.submit-btn {
  width: 140rpx;
  height: 80rpx;
  line-height: 80rpx;
  background: var(--td-brand-color);
  color: #ffffff;
  font-size: 28rpx;
  font-weight: 500;
  border-radius: 12rpx;
  text-align: center;
  border: none;
  transition: all 0.3s ease;

  &:active {
    transform: scale(0.98);
    opacity: 0.9;
  }
}

.error-message {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60rpx;
  text-align: center;
  background: #ffffff;
  margin: 20rpx;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);

  text {
    font-size: 28rpx;
    color: #666666;
    margin-bottom: 30rpx;
  }
}

.refresh-btn {
  margin-top: 20rpx;
  background: var(--td-brand-color);
  color: #ffffff;
  font-size: 28rpx;
  font-weight: 500;
  border-radius: 12rpx;
  padding: 16rpx 40rpx;
  transition: all 0.3s ease;

  &:active {
    transform: scale(0.98);
    opacity: 0.9;
  }
}

.loading {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 60rpx;
}
</style>
